const sessionStorage = window.sessionStorage
const localStorage = window.localStorage

module.exports = {
	$U_SetCacheItem: sessionSet,

	$U_GetCacheItem: sessionGet,

	$U_RemoveCacheItem(key) {
		if (!sessionStorage || typeof sessionStorage.removeItem != 'function')
			return false
		return sessionStorage.removeItem(key)
	},

	$U_SetItem: localSet,

	$U_GetItem: localGet,

	$U_RemoveItem(key) {
		if (!localStorage || typeof localStorage.removeItem != 'function')
			return false
		return localStorage.removeItem(key)
	},

	$U_LocalUserInfo(key, val) {
		if (typeof key == 'object') {
			return localSet('user', key)
		} else if (typeof key == 'string' && typeof val == 'object') {
			return localSet(`user-${key}`, val)
		} else if (typeof key == 'string' && !val) {
			return localGet(`user-${key}`) || {}
		}
		return localGet('user') || {}
	},

	$U_UserInfo(val) {
		if (val === null)
			return sessionStorage.removeItem('user')
		if (typeof val == 'object') {
			return sessionSet('user', val)
		}
		return sessionGet('user') || null
	},
}

function sessionSet(key, value) {
	if (!sessionStorage || typeof sessionStorage.setItem != 'function')
		return false
	if (typeof value == 'object') {
		value = JSON.stringify(value)
	}
	return sessionStorage.setItem(key, value)
}

function sessionGet(key) {
	if (!sessionStorage || typeof sessionStorage.getItem != 'function')
		return false
	let result = null
	try {
		result = JSON.parse(sessionStorage.getItem(key))
	} catch (e) {
		result = sessionStorage.getItem(key) || null
	}
	return result
}

function localSet(key, value) {
	if (!localStorage || typeof localStorage.setItem != 'function')
		return false
	if (typeof value == 'object') {
		value = JSON.stringify(value)
	}
	return localStorage.setItem(key, value)
}

function localGet(key, org) {
	if (!localStorage || typeof localStorage.getItem != 'function')
		return false
	if (org === true)
		return localStorage.getItem(key)
	let result = null
	try {
		result = JSON.parse(localStorage.getItem(key))
	} catch (e) {
		console.log(e)
		result = localStorage.getItem(key) || null
	}
	return result
}